package com.smxy.mall.service.impl;

import com.smxy.mall.dao.CarDao;
import com.smxy.mall.dao.GoodsDao;
import com.smxy.mall.entity.Category;
import com.smxy.mall.entity.Goods;
import com.smxy.mall.model.Current;
import com.smxy.mall.model.request.GoodsReq;
import com.smxy.mall.model.response.CarNumRes;
import com.smxy.mall.model.response.GoodsResponse;
import com.smxy.mall.service.CategoryService;
import com.smxy.mall.service.GoodsService;
import com.smxy.mall.utils.Common;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private CategoryService categoryService;
    @Resource
    private CarDao carDao;

    /**
     * 添加商品
     * @param goodsReq
     * @return
     */
    @Override
    public Goods save(GoodsReq goodsReq) {
        Goods goods = new Goods();
        goods.setGoodsName(goodsReq.getGoodsName());
        goods.setCover(goodsReq.getCover());
        goods.setPrice(goodsReq.getPrice());
        goods.setLinePrice(goodsReq.getLinePrice());
        goods.setImgs(goodsReq.getImgs());
        goods.setDetail(goodsReq.getDetail());
        goods.setNum(goodsReq.getNum());
        goods.setInfo(goodsReq.getInfo());
        if(!StringUtils.isEmpty(goodsReq.getId())){
            goods.setId(goodsReq.getId());
        }
        return goodsDao.save(goods);
    }

    /**
     * 全部/分类 商品列表
     * @param categoryId
     * @param pageable
     * @return
     */
    @Override
    public Page<Goods> goodsList(Integer categoryId, Pageable pageable){
        if(StringUtils.isEmpty(categoryId)){
            return goodsDao.findAll(pageable); //全部商品
        }else{
            return goodsDao.findByCategoryId(categoryId,pageable);  //分类商品
        }
    }

    /**
     * 商品详情
     * @param id
     * @return
     */
    @Override
    public Goods goodsInfo(Integer id) {
        return goodsDao.findById(id);
    }

    @Override
    public List<GoodsResponse> recommendList() {
        return goodsDao.recommendList();
    }

    @Override
    public List<Object> goodsListGroup(Integer shopId) {
        List<Category> categories = categoryService.list(shopId);
        List<Object> list = new ArrayList<>();
        categories.forEach(item -> {
            Map<String,Object> map = new HashMap<>();
            map.put("categoryName",item.getCategoryName());
            map.put("categoryIcon",item.getCategoryIcon());
            map.put("categoryId",item.getId());
            map.put("list",goodsDao.findByCategoryId(item.getId()));
            list.add(map);
        });
        return list;
    }
}
